<?php
namespace app\command;

use app\admin\model\course\Order;
use app\admin\model\Third;
use EasyWeChat\Factory;
use extendwechat\Message;
use think\Cache;
use think\console\Command;
use think\console\Input;
use think\console\Output;
use think\Db;
class SyncFans extends Command
{

    protected function configure()
    {
        $this->setName('syncfans')
            ->setDescription('同步粉丝');
    }

    protected function execute(Input $input, Output $output)
    {

        $output->writeln("同步粉丝");

        $config = get_addon_config('third');
//        dump($config['wechatWeb']);exit;
        $app = Factory::officialAccount($config['wechatWeb']);
        $messageModel = new Message();
        $list = $messageModel->getFansList();
        $old_list = Third::where("platform","wechatWeb")->column("openid");
        $new_list = array_diff($list, $old_list);
        $output->writeln("粉丝数量".count($new_list));


        $save_user_list = [];

        $group_count = 1;
        if(count($new_list) > 0){
            $userChunkList = array_chunk($list,100);
            foreach ($userChunkList as $chunk_list){
                $output->writeln("获取第".$group_count."组粉丝");
                $chunk_user_list = $app->user->select($chunk_list);

                if(isset($chunk_user_list['user_info_list']) &&count($chunk_user_list['user_info_list'])>0){
                    $save_user_list = array_merge($save_user_list,$chunk_user_list['user_info_list']);
                }
                $group_count ++ ;
            }
            foreach ($save_user_list as $key => &$user){

                $user['nickname'] = "微信用户";
                try {
                    \addons\third\library\Service::connect("wechatWeb", $user, []);
                    $output->writeln("同步成功,openid:".$user['openid']);
                }catch (\Exception $e){
                    dump($user);
                }

            }


            dump("同步粉丝成功：数量:".count($save_user_list));
        }


    }




}